package com.djq.hhc.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.djq.hhc.feign.CreditExchangeFeignClient;
import com.djq.hhc.feign.CreditInfoFeignClient;
import com.djq.hhc.holder.UserHolder;
import com.djq.hhc.mapper.ShopOrderMapper;
import com.djq.hhc.model.shop.ShopGoods;
import com.djq.hhc.model.shop.ShopOrder;
import com.djq.hhc.result.Result;
import com.djq.hhc.service.ShopGoodsService;
import com.djq.hhc.service.ShopOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.djq.hhc.redis.RedisConstants.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: dadd7
 * @Date: 2023/03/05/下午 4:56
 * @Description:
 */

@Service
public class ShopOrderServiceImpl extends ServiceImpl<ShopOrderMapper, ShopOrder> implements ShopOrderService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ShopGoodsService shopGoodsService;

    @Autowired
    private CreditInfoFeignClient creditInfoFeignClient;

    @Autowired
    private CreditExchangeFeignClient creditExchangeFeignClient;

    @Override
    @Transactional
    public void orderPast(ShopOrder shopOrder) {
        //删除用户订单
        Long orderId = shopOrder.getId();
        update().setSql("status = 0").eq("id", orderId).update();
        //商品库存+1
        Long goodsId = shopOrder.getGoodsId();
        shopGoodsService.update().setSql("num = num + 1").eq("id", goodsId).update();
        //删除商品的redis
        stringRedisTemplate.delete(SHOP_GOODS_KEY + goodsId);
    }

    @Override
    @Transactional
    public Result submitOrder(String token, Long id) {
        ShopOrder order = getById(id);
        ShopGoods goods = shopGoodsService.getById(order.getGoodsId());
        //判断redis时间
        String s = stringRedisTemplate.opsForValue().get(SHOP_ORDER_KEY + id);
        if (s == null) {
            return Result.fail().message("订单已过期");
        }
        Integer credit = creditInfoFeignClient.getCredit(token, String.valueOf(order.getBuyerId()));
        //生成积分使用表
        creditExchangeFeignClient.exchange(token, String.valueOf(id), credit, goods.getPrice());
        //扣除积分
        boolean b = creditInfoFeignClient.discountCredit(token, goods.getPrice(), credit);
        if (!b) {
            return Result.fail().message("操作失败：请勿同时兑换多个");
        }
        //订单设置成完成
        boolean update = update().setSql("status = 2").eq("id", order.getId()).eq("status", 1).update();
        if (!update) {
            return Result.fail().message("订单已过期或者不存在");
        }
        stringRedisTemplate.delete(SHOP_ORDER_KEY + id);

        String key = NOW_USER_KEY + UserHolder.getUser().getId();
        stringRedisTemplate.delete(key);
        return Result.ok().message("兑换成功！");
    }
}
